package com.yuqih.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

public class ZipUtils {

	public static void compress(OutputStream ous, File file) throws IOException {
		if (!file.exists()) {
			throw new IllegalArgumentException("文件不存在");
		}

		ZipArchiveOutputStream zous = null;
		try {
			zous = new ZipArchiveOutputStream(ous);
			zous.setEncoding(StandardCharsets.UTF_8.name());
			String rootPath = file.getParent();
			if (rootPath == null) {
				throw new IllegalArgumentException("文件没有上级路径");
			}
			rootPath = rootPath + File.separator;
			doCompress(zous, file, rootPath);
		} finally {
			IOUtils.closeQuietly(zous);
		}

	}

	private static void doCompress(ZipArchiveOutputStream zous, File file, String rootPath) throws IOException {
		String name = file.getPath();
		name = StringUtils.removeStart(name, rootPath);
		if (file.isDirectory()) {
			name = name + "/";
		}

		ZipArchiveEntry entry = new ZipArchiveEntry(name);
		zous.putArchiveEntry(entry);
		if (file.isDirectory()) {
			zous.closeArchiveEntry();
			File[] files = file.listFiles();
			for (File f : files) {
				doCompress(zous, f, rootPath);
			}
		} else {
			FileInputStream fins = null;
			try {
				fins = FileUtils.openInputStream(file);
				IOUtils.copy(fins, zous);
				zous.closeArchiveEntry();
			} finally {
				IOUtils.closeQuietly(fins);
			}
		}

	}
}
